package controllerAnts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/panjf2000/ants/v2"
	"sync"
	"sync/atomic"
	"time"
)

// 处理业务
func demo() {
	time.Sleep(10 * time.Millisecond) // 10毫秒
	fmt.Println("Hello World!")
}

var sum int32

// 处理业务
func myFunc(i interface{}) {
	n := i.(int32)
	atomic.AddInt32(&sum, n)
	fmt.Printf("run with %d\n", n)
}
func Ants() gin.HandlerFunc {
	return func(context *gin.Context) {

		defer ants.Release() //释放

		// 使用公共的pool
		runTime := 10
		var wg sync.WaitGroup
		syncCalculateSum := func() {
			demo()
			wg.Done()
		}
		for i := 0; i < runTime; i++ {
			wg.Add(1)
			_ = ants.Submit(syncCalculateSum)
		}
		wg.Wait()
		fmt.Printf("running goroutines: %d\n", ants.Running()) //获取进程数量
		fmt.Printf("finish all tasks.\n")

		p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {
			myFunc(i)
			wg.Done()
		})
		p.Release()
		// Submit tasks one by one.
		for i := 0; i < runTime; i++ {
			wg.Add(1)
			_ = p.Invoke(int32(i))
		}
		wg.Wait()
		fmt.Printf("running goroutines: %d\n", p.Running())
		fmt.Printf("finish all tasks, result is %d\n", sum)
	}

}
